#include "widget.h"
#include "ui_widget.h"

Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);
    setWindowTitle("圣遗物记录");
    resize(450,1000);
    this->move(1450, 0);
    btn->setText("截图");

    btn6->setText("强化识图");
    btn6->move(100,0);

    btn7->setText("结果识图");
    btn7->move(200,0);

    btn3->setText("刷本识图");
    btn3->move(300,0);


    lable->move(10,30);
    lable->resize(400, 500);

    btn4->setText("保存txt");
    btn4->move(10,540);

    btn5->setText("当前获取套装");
    btn5->move(110,540);

    btn1->setText("获取令牌");
    btn1->move(210,540);

    btn2->setText("自动截图");
    btn2->move(310,540);

    text->move(10,580);
    text->resize(400,400);


    connect(btn,&QPushButton::clicked,[=]{
        ScreenWidget::Instance()->showFullScreen();
    });
    connect(btn1,&QPushButton::clicked,[=]{
        /*QRect rect = ScreenWidget::self->rect;
        qDebug()<<rect.x()<<","<<rect.y();
        qDebug()<<rect.width()<<","<<rect.height();//*/
        //getAcc();

    });
    connect(btn2,&QPushButton::clicked,[=]{
        getImage();
        btnFlag = 1;
        distinguishC();
    });
    connect(btn3,&QPushButton::clicked,[=]{
        getImage();
        btnFlag = 1;
        distinguishC();
    });
    connect(btn4,&QPushButton::clicked,[=]{
        saveTxt();
    });
    connect(btn5,&QPushButton::clicked,[=]{
        if(isQTao){
            btn5->setText("当前不获取套装");
            isQTao = !isQTao;
        }else {
            btn5->setText("当前获取套装");
            isQTao = !isQTao;
        }
    });
    connect(btn6,&QPushButton::clicked,[=]{
        getImage();
        btnFlag = 2;
        distinguishC();
    });
    connect(btn7,&QPushButton::clicked,[=]{
        getImage2();
        btnFlag = 3;
        distinguishC();
    });
    TEST();
    iniAcc();
    //ScreenWidget::isAuto = true;
}

void Widget::distinguishC()
{
    QString parm = imageStr;
    if(parm.isEmpty()){
        QMessageBox::information(NULL, "错误", "图像数据不能为空");
        return;
    }
    //text->append("图像加载成功");
    //text->append(accessToken);
    nam = new QNetworkAccessManager(this);
    QUrl url;
    //url.setUrl("https://aip.baidubce.com/rest/2.0/ocr/v1/general_basic?access_token="+accessToken);
    url.setUrl("https://aip.baidubce.com/rest/2.0/ocr/v1/accurate_basic?access_token="+accessToken);

    QNetworkRequest request;
    request.setUrl(url);
    request.setHeader(QNetworkRequest::ContentTypeHeader,QVariant("application/x-www-form-urlencoded"));
    QByteArray byteArr;
    byteArr.append("image=");
    byteArr.append(QUrl::toPercentEncoding(parm));
    connect(nam, &QNetworkAccessManager::finished,this, &Widget::recognitionRequestFinished);
    QNetworkReply* reply = nam->post(request,byteArr);
}


//废弃使用
/*void Widget::distinguish()
{
    Py_Initialize();
    if (!Py_IsInitialized())
    {
        printf("ini err!\n");
        return ;
    }
    PyRun_SimpleString("import sys");
    PyRun_SimpleString("sys.path.append('D:/qtd/yun-cs2/')");
    PyObject* pModule = PyImport_ImportModule("yun");
    if (!pModule) {
        printf("Cant open python file!\n");
        return ;
    }
    PyObject* pFunhello = PyObject_GetAttrString(pModule, "jc");
    if (!pFunhello){
        qDebug() << "Get function jc failed";
        return ;
    }
    PyObject* pRet = PyObject_CallFunction(pFunhello, NULL);

    /*QFile file("testtext.txt");
    if (!file.open(QIODevice::ReadOnly)) {
        qDebug()<<"err1";
        return ;
    }
    QTextStream stream(&file);
    stream.setCodec("UTF-8");
    QString data;
    int i = 0;
    while(1)
    {
        stream>>data;
        if(data==NULL)
            break;
        i++;
        qDebug()<<"["<<i<<"]"<<data;
    }//*




    Py_Finalize();
}//*/

void Widget::getWindowsXY()
{

}

void Widget::getImage()
{

    /*QWindow *window=windowHandle();
    QScreen *screen=window->screen();

    QPixmap pixmap=screen->grabWindow(0);
    QLabel *label=new QLabel(this);
    label->setPixmap(pixmap);
    label->show();

    pixmap.save("1.png");//*/

    QRect rect = ScreenWidget::self->rect;
    QPixmap pixmap = screen->grabWindow(0,rect.x(), rect.y()
                                    ,rect.width() ,rect.height());
    lable->wordWrap();
    lable->setPixmap(pixmap);
    lable->setScaledContents(true);

    pixmap.save("1.png");
    QImage image = pixmap.toImage();
    QByteArray ba;
    QBuffer buf(&ba);
    image.save(&buf, "jpg");
    QByteArray hexed = ba.toBase64();
    buf.close();
    imageStr = hexed;


    /*QString format = "png";
    QString initialPath = QDir::currentPath()+tr("/untitled.")+format;
    QString fileName = QFileDialog::getSaveFileName(this, tr("Save As"),
                                                    initialPath,
                                                    tr("%1 Files (*.%2);;AllFiles (*)").arg(format.toUpper().arg(format)));
    if(!fileName.isEmpty()){
        fullScreen.save(fileName, format.toLatin1());
        QMessageBox::information(this, "success", "截屏保存成功");
    }//*/
}

void Widget::getImage2()
{
    QRect rect = ScreenWidget::self->rect2;
    QPixmap pixmap = screen->grabWindow(0,rect.x(), rect.y()
                                    ,rect.width() ,rect.height());
    lable->wordWrap();
    lable->setPixmap(pixmap);
    lable->setScaledContents(true);

    pixmap.save("1.png");
    QImage image = pixmap.toImage();
    QByteArray ba;
    QBuffer buf(&ba);
    image.save(&buf, "jpg");
    QByteArray hexed = ba.toBase64();
    buf.close();
    imageStr = hexed;
}

void Widget::appText()
{
    QString data;
    QString txt="";
    QString lv="";
    isStart = false;
    qDebug()<<wordsNum;
    qDebug()<<jsonArr;
    for(int i=0; i<wordsNum; i++)
    {
        data = jsonArr[i].toObject().take("words").toString();
        //text->append(data);
        QString str = appToText(data);
        if(str != NULL){
            if(str == "s"){
                if(txt == "3"||txt == "4"||txt == "5")
                    str = "S";
            }
            if(str == "g"){
                if(txt == "3"||txt == "4"||txt == "5")
                    str = "G";
            }
            if(str == "f"){
                if(txt == "3"||txt == "4"||txt == "5")
                    str = "F";
            }
            if(str == "5★"||str == "4★"||str == "3★"){
                lv=str;
                continue;
            }
            if(!isTao){                     //不是套装信息
                txt = txt + str;
            }else if(isTao || txt != ""){   //是套装信息
                txt = str + txt;
                isTao = false;
                break;
            }
        }
    }
    if(lv == "5★"){
        txt = "<span style='color:#bc6932'>" + txt +"   5★<span>";
    }else if(lv == "4★"){
        txt = "<span style='color:#a156e0'>" + txt +"   4★<span>";
    }else if(lv == "3★"){
        txt = "<span style='color:#5180cb'>" + txt +"   3★<span>";
    }
    text->append(txt);
}

void Widget::appTextQ()
{
    QString key,value;
    QString txt="";
    QString lv="";
    isStart = false;
    qDebug()<<wordsNum;
    qDebug()<<jsonArr;
    for(int i=0; i<wordsNum; i += 2)
    {
        key = jsonArr[i].toObject().take("words").toString();
        value = jsonArr[i+1].toObject().take("words").toString();
        QString str = appToTextQ(key, value);

        txt = txt + str;
    }
    text->append(txt);
}

void Widget::appTextO()
{
    QString key,value1,value2;
    QString txt="";
    QString lv="";
    isStart = false;
    qDebug()<<wordsNum;
    qDebug()<<jsonArr;
    for(int i=0; i<wordsNum; i += 3)
    {
        key = jsonArr[i].toObject().take("words").toString();
        value1 = jsonArr[i+1].toObject().take("words").toString();
        value2 = jsonArr[i+2].toObject().take("words").toString();
        QString str = appToTextO(key, value1, value2);
        if(str != NULL){
            txt = txt + "【" + str + "】";
        }//*/

    }
    txt = "\t" + txt;
    text->moveCursor(QTextCursor::End);
    text->insertPlainText(txt);
}

QString Widget::appToText(QString data)
{
    qDebug()<<data;
    if(data.contains("生之花",Qt::CaseSensitive)){
        isStart = true;
        return "1";
    }else if(data.contains("死之羽",Qt::CaseSensitive)){
        isStart = true;
        return "2";
    }else if(data.contains("时之沙",Qt::CaseSensitive)){
        isStart = true;
        return "3";
    }else if(data.contains("空之杯",Qt::CaseSensitive)){
        isStart = true;
        return "4";
    }else if(data.contains("理之冠",Qt::CaseSensitive)){
        isStart = true;
        return "5";
    }
    if("★★★★★" == data || data == "★★★★自"){
        return "5★";
    }else if ("★★★★" == data) {
        return "4★";
    }else if ("★★★" == data) {
        return "3★";
    }

    if(data.contains("生命值",Qt::CaseSensitive)){
        if(data.contains("%",Qt::CaseSensitive)){
            return "S";
        }else {
            return "s";
        }
    }else if(data.contains("攻击力",Qt::CaseSensitive)){
        if(data.contains("%",Qt::CaseSensitive)){
            return "G";
        }else {
            return "g";
        }
    }else if(data.contains("防御力",Qt::CaseSensitive)){
        if(data.contains("%",Qt::CaseSensitive)){
            return "F";
        }else {
            return "f";
        }
    }else if(data.contains("精通",Qt::CaseSensitive)){
        return "j";
    }else if(data.contains("充能",Qt::CaseSensitive)){
        return "c";
    }else if(data.contains("暴击率",Qt::CaseSensitive)){
        return "b";
    }else if(data.contains("暴击伤害",Qt::CaseSensitive)){
        return "B";
    }else if(data.contains("伤害加成",Qt::CaseSensitive)){
        return "y";
    }else if(data.contains("治疗",Qt::CaseSensitive)){
        return "z";
    }

    //如果不记录套装，就跳出
    if(!isQTao){
        return NULL;
    }
    //以下记录，首先是按照绝缘本，冰本记录，然后根据米游社顺序记录
    if(data.contains("行者",Qt::CaseSensitive) && isStart){
        isTao = true;
        return "行者";
    }else if(data.contains("奇迹",Qt::CaseSensitive) && isStart){
        isTao = true;
        return "奇迹";
    }else if(data.contains("追忆",Qt::CaseSensitive) && isStart){
        isTao = true;
        return "追忆";
    }else if(data.contains("绝缘",Qt::CaseSensitive) && isStart){
        isTao = true;
        return "绝缘";
    }else if(data.contains("守护",Qt::CaseSensitive) && isStart){
        isTao = true;
        return "守护";
    }else if(data.contains("赌徒",Qt::CaseSensitive) && isStart){
        isTao = true;
        return "赌徒";
    }else if(data.contains("沉沦",Qt::CaseSensitive) && isStart){
        isTao = true;
        return "沉沦";
    }else if(data.contains("冰风",Qt::CaseSensitive) && isStart){
        isTao = true;
        return "冰风";
    }else if(data.contains("华馆",Qt::CaseSensitive) && isStart){
        isTao = true;
        return "华馆";
    }else if(data.contains("海染",Qt::CaseSensitive) && isStart){
        isTao = true;
        return "海染";
    }else if(data.contains("千岩",Qt::CaseSensitive) && isStart){
        isTao = true;
        return "千岩";
    }else if(data.contains("苍白",Qt::CaseSensitive) && isStart){
        isTao = true;
        return "苍白";
    }else if(data.contains("平息",Qt::CaseSensitive) && isStart){
        isTao = true;
        return "平雷";
    }else if(data.contains("魔女",Qt::CaseSensitive) && isStart){
        isTao = true;
        return "魔女";
    }else if(data.contains("流浪",Qt::CaseSensitive) && isStart){
        isTao = true;
        return "乐团";
    }else if(data.contains("染血",Qt::CaseSensitive) && isStart){
        isTao = true;
        return "骑士";
    }else if(data.contains("少女",Qt::CaseSensitive) && isStart){
        isTao = true;
        return "少女";
    }else if(data.contains("角斗",Qt::CaseSensitive) && isStart){
        isTao = true;
        return "角斗";
    }else if(data.contains("渡过烈火",Qt::CaseSensitive) && isStart){
        isTao = true;
        return "渡火";
    }else if(data.contains("磐岩",Qt::CaseSensitive) && isStart){
        isTao = true;
        return "磐岩";
    }else if(data.contains("如雷",Qt::CaseSensitive) && isStart){
        isTao = true;
        return "如雷";
    }else if(data.contains("逆飞",Qt::CaseSensitive) && isStart){
        isTao = true;
        return "逆飞";
    }else if(data.contains("宗室",Qt::CaseSensitive) && isStart){
        isTao = true;
        return "宗室";
    }else if(data.contains("翠绿",Qt::CaseSensitive) && isStart){
        isTao = true;
        return "风套";
    }else if(data.contains("勇士",Qt::CaseSensitive) && isStart){
        isTao = true;
        return "勇士";
    }else if(data.contains("教官",Qt::CaseSensitive) && isStart){
        isTao = true;
        return "教官";
    }else if(data.contains("流放",Qt::CaseSensitive) && isStart){
        isTao = true;
        return "流放";
    }else if(data.contains("祭冰",Qt::CaseSensitive) && isStart){
        isTao = true;
        return "祭冰";
    }else if(data.contains("祭雷",Qt::CaseSensitive) && isStart){
        isTao = true;
        return "祭雷";
    }else if(data.contains("祭火",Qt::CaseSensitive) && isStart){
        isTao = true;
        return "祭火";
    }else if(data.contains("祭水",Qt::CaseSensitive) && isStart){
        isTao = true;
        return "祭水";
    }else if(data.contains("狂战",Qt::CaseSensitive) && isStart){
        isTao = true;
        return "狂战";
    }else if(data.contains("武人",Qt::CaseSensitive) && isStart){
        isTao = true;
        return "武人";
    }else if(data.contains("学士",Qt::CaseSensitive) && isStart){
        isTao = true;
        return "学士";
    }else if(data.contains("幸运儿",Qt::CaseSensitive) && isStart){
        isTao = true;
        return "幸运";
    }else if(data.contains("游医",Qt::CaseSensitive) && isStart){
        isTao = true;
        return "游医";
    }
    //switch(data){}    //似乎不能使用QString类型

    return NULL;
}

QString Widget::appToTextQ(QString key, QString value)
{
    if(key.contains("生命值",Qt::CaseSensitive)){
        if(value.contains("%",Qt::CaseSensitive)){
            return "S";
        }else {
            return "s";
        }
    }else if(key.contains("攻击力",Qt::CaseSensitive)){
        if(value.contains("%",Qt::CaseSensitive)){
            return "G";
        }else {
            return "g";
        }
    }else if(key.contains("防御力",Qt::CaseSensitive)){
        if(value.contains("%",Qt::CaseSensitive)){
            return "F";
        }else {
            return "f";
        }
    }else if(key.contains("精通",Qt::CaseSensitive)){
        return "j";
    }else if(key.contains("充能",Qt::CaseSensitive)){
        return "c";
    }else if(key.contains("暴击率",Qt::CaseSensitive)){
        return "b";
    }else if(key.contains("暴击伤害",Qt::CaseSensitive)){
        return "B";
    }else if(key.contains("伤害加成",Qt::CaseSensitive)){
        return "y";
    }else if(key.contains("治疗",Qt::CaseSensitive)){
        return "z";
    }
    return NULL;
}

QString Widget::appToTextO(QString key, QString value1, QString value2)
{
    QString v1cs = value1,v2cs = value2;
    double v1 = value1.remove('%').toDouble();
    double v2 = value2.remove('%').toDouble();
    qDebug()<<key<<","<<value1<<","<<value2<<","<<v2cs;
    qDebug()<<key<<","<<v1<<","<<v2;

    QString vj = QString::number(v2-v1);
    qDebug()<<vj;
    if(key.contains("生命值",Qt::CaseSensitive)){
        if(v1cs.contains("%",Qt::CaseSensitive)||v2cs.contains("%",Qt::CaseSensitive)){
            return "S"+vj;
        }else {
            return "s"+vj;
        }
    }else if(key.contains("攻击力",Qt::CaseSensitive)){
        if(v1cs.contains("%",Qt::CaseSensitive)||v2cs.contains("%",Qt::CaseSensitive)){
            return "G"+vj;
        }else {
            return "g"+vj;
        }
    }else if(key.contains("防御力",Qt::CaseSensitive)){
        if(v1cs.contains("%",Qt::CaseSensitive)||v2cs.contains("%",Qt::CaseSensitive)){
            return "F"+vj;
        }else {
            return "f"+vj;
        }
    }else if(key.contains("精通",Qt::CaseSensitive)){
        return "j"+vj;
    }else if(key.contains("充能",Qt::CaseSensitive)){
        return "c"+vj;
    }else if(key.contains("暴击率",Qt::CaseSensitive)){
        qDebug()<<value1<<v1;
        qDebug()<<value2<<v2;
        return "b"+vj;
    }else if(key.contains("暴击伤害",Qt::CaseSensitive)){
        return "B"+vj;
    }
    return NULL;
}

void Widget::saveTxt()
{
    QString path = QFileDialog::getSaveFileName(this, "save", "../", "TXT(*.txt)");
    QFile file(path);
    if (!file.open(QIODevice::WriteOnly)) {
        qDebug()<<"err open";
        return ;
    }
    QString str = text->toPlainText();
    file.write(str.toUtf8());
    file.close();

}

void Widget::getAccC()
{
    QFile file("testacc.txt");
    if(!file.open(QIODevice::ReadOnly)){
        qDebug()<<"err open";
        return;
    }
    QTextStream stream(&file);
    QString key,secret;
    stream>>key;
    stream>>secret;
    //key = "2iu2FzEdzzFuYwhMDdtt7kGK";
    //secret = "1gmhHKZ2NH82BhT9cZsdHa4KC9keiXUP";
    QSettings *configIniWrite = new QSettings("set.ini", QSettings::IniFormat);
    //向ini文件中写入内容,setValue函数的两个参数是键值对
    configIniWrite->setValue("key", key);
    configIniWrite->setValue("secret", secret);
    //写入完成后删除指针
    delete configIniWrite;
    QMessageBox::information(NULL, "成功", "保存成功");
}


//废弃使用
/*void Widget::getAcc()
{
    Py_Initialize();
    if (!Py_IsInitialized())
    {
        return ;
    }
    PyRun_SimpleString("import sys");
    PyRun_SimpleString("sys.path.append('D:/qtd/yun-cs2/')");
    PyObject* pModule = PyImport_ImportModule("yun");
    if (!pModule) {
        printf("Cant open python file!\n");
        return ;
    }
    PyObject* pFunhello = PyObject_GetAttrString(pModule, "ini");
    if (!pFunhello){
        qDebug() << "Get function ini failed";
        return ;
    }
    PyObject* pRet = PyObject_CallFunction(pFunhello, NULL);
}//*/

void Widget::TEST()
{
    /*qDebug()<<"1";
    QString s = "'7.0%'},";
    //QString s = "7.2%";
    QString c = s.remove('\'').remove('%').remove(',').remove('}');

    qDebug()<<c;
    double a = s.toDouble();
    qDebug()<<a;//*/
}

void Widget::iniAcc()
{
    QFile file("testacc.txt");
    if(!file.open(QIODevice::ReadOnly)){
        qDebug()<<"err open";
        return;
    }
    QTextStream stream(&file);
    QString key,secret;
    stream>>key;
    stream>>secret;
    stream>>accessToken;
    file.close();
    //text->append(key);
    //text->append(secret);
    //key = "2iu2FzEdzzFuYwhMDdtt7kGK";
    //secret = "1gmhHKZ2NH82BhT9cZsdHa4KC9keiXUP";
    QSettings *configIniWrite = new QSettings("set.ini", QSettings::IniFormat);
    //向ini文件中写入内容,setValue函数的两个参数是键值对
    configIniWrite->setValue("key", key);
    configIniWrite->setValue("secret", secret);
    QDateTime time = QDateTime::currentDateTime();
    int timeT = time.toTime_t();
    if((configIniWrite->value("tokenTime").toInt() + 30*24*3600) < timeT){
        QMessageBox::information(NULL, "未成功", "未初始化成功");
        //QMessageBox::information(NULL, "未成功", configIniWrite->value("accessToken").toString());
        nam = new QNetworkAccessManager(this);
        QString parm = "https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id="+key+"&client_secret="+secret+"&";
        QUrl url(parm);
        connect(nam, &QNetworkAccessManager::finished,this, &Widget::getAccessTokenRequestFinished);
        QNetworkReply* reply = nam->get(QNetworkRequest(url));
    }else {
        //accessToken = configIniWrite->value("accessToken").toString();
        //accessToken = "24.cecc5302c9bf36cac2e2d04a778164c6.2592000.1648474599.282335-24068540";
        //text->append(accessToken);
        QMessageBox::information(NULL, "成功", "初始化成功");
    }
    //写入完成后删除指针
    delete configIniWrite;

}

void Widget::paintEvent(QPaintEvent *event)
{
}

Widget::~Widget()
{
    delete ui;
    exit(0);
}

void Widget::recognitionRequestFinished(QNetworkReply *reply)
{
    //text->append("R:进入");
    QNetworkReply::NetworkError err = reply->error();
    int errInt = err;
    //text->append("err:"+QString::number(errInt));
    //qDebug()<<reply->readAll();
    //QNetworkReply::UnknownNetworkError;
    if(err != QNetworkReply::NoError) {
        //text->append("R:if 进入");
        qDebug() << "Failed: " << reply->errorString();
    }else {
        // 获取返回内容
        //text->append("R:else 进入");
        QJsonParseError json_error;
        QJsonDocument parse_doucment = QJsonDocument::fromJson(reply->readAll(), &json_error);
        if(parse_doucment.isObject()){
            textObj = parse_doucment.object();
            wordsNum = textObj.take("words_result_num").toInt();
            if(wordsNum > 0){
                jsonArr = textObj.take("words_result").toArray();
                /*QString res;
                qDebug()<<jsonArr;
                for(int i=0;i<wordsNum;i++){
                   res.append(jsonArr[i].toObject().take("words").toString());
                   res.append("<br>");
                }
                text->setText(res);//*/
            }else{
                QMessageBox::information(NULL, "提示", "无法识别图片内容");
            }
            //QJsonArray textJson = textObj.take("words_result").toArray();
            //QString textStr = QString(QJsonDocument(obj).toJson(QJsonDocument::Compact));
            //qDebug()<<textStr;
        }
    }
    //text->append("R:0");
    nam->deleteLater();
    if(1 == btnFlag) {
        //text->append("R:1");
        appText();
    }else if(2 == btnFlag){
        //text->append("R:2");
        appTextQ();
    }else if(3 == btnFlag){
        //text->append("R:3");
        appTextO();
    }
}

void Widget::getAccessTokenRequestFinished(QNetworkReply *reply)
{
    QNetworkReply::NetworkError err = reply->error();
    if(err != QNetworkReply::NoError) {
        qDebug() << "Failed: " << reply->errorString();
    }else {
        // 获取返回内容
        QJsonParseError json_error;
        QJsonDocument parse_doucment = QJsonDocument::fromJson(reply->readAll(), &json_error);
        if(parse_doucment.isObject()){
            QJsonObject obj = parse_doucment.object();
            accessToken = obj.take("access_token").toString();
            QSettings *configIniWrite = new QSettings("set.ini", QSettings::IniFormat);
            //向ini文件中写入内容,setValue函数的两个参数是键值对
            configIniWrite->setValue("accessToken", accessToken);
            QDateTime time = QDateTime::currentDateTime();   //获取当前时间
            int timeT = time.toTime_t();   //将当前时间转为时间戳
            configIniWrite->setValue("tokenTime", timeT);
            //写入完成后删除指针
            delete configIniWrite;
        }
    }
    nam->deleteLater();
}

